package tcpdemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerThread extends  Thread{
    //重写run方法
    public  void  run(){
        //服务器ServerSocket
        try {
            ServerSocket serverSocket= new ServerSocket(9901);
            //死循环，服务器一直处于运转的状态
            while (true){
               //创建一个用于接收客户端的socket
                Socket socket = serverSocket.accept();

                //使用socket和客户端进行通信
                System.out.println("/////////////接收信息/////////////////////");
                /////////////接收信息/////////////////////
                //获取socket的输入流对象
                BufferedReader bufferedReader = new
                        BufferedReader
                        (new InputStreamReader(socket.getInputStream()));

                //读取信息
                while (true){
                    String str = bufferedReader.readLine();
                    if (str !=null &&!str.equals("eof")){
                        //业务逻辑处理的地方
                        System.out.println("服务器："+str);
                    }else {
                        //终止循环读取信息
                        break;
                    }
                }

                //////////////发送信息/////////////////
                System.out.println("//////////////发送信息/////////////////");
                //获取socketde 输出流对象
                BufferedWriter bufferedWriter = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                );
                //发送消息
                String strMsg = "你好 too，客户端===============";
                System.out.println("服务器："+strMsg);
                bufferedWriter.write(strMsg);
                //附件一个回车符
                bufferedWriter.newLine();//相当于一个换行符
                bufferedWriter.write("eof");
                bufferedWriter.write("\n");
                //清空输出流的发送区域，将信息发送到网络上
                bufferedWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
